<?php

declare (strict_types=1);

namespace app\middleware;

use app\common\service\GlobalsVariableService;
use think\facade\Log;
use think\Request;

class Base
{
    /**
     * 请求信息
     * @var Request
     */
    protected $request;

    /**
     * 保存请求信息
     * Base constructor.
     * @throws
     */
    public function __construct()
    {
        // 保存全局变量
        $this->request = app(Request::class);
        $header = $this->request->header();
        foreach ($header as $key => $val) {
            GlobalsVariableService::set($key, $val);
        }
    }

    /**
     * 获取路由信息
     * @return array
     */
    protected function getRouteInfo(): array
    {
        $request = app(Request::class);
        return [
            'rule' => $request->rule()->getRule(),
            'route' => $request->rule()->getRoute(),
            'option' => $request->rule()->getOption(),
            'var' => $request->rule()->getVars(),
        ];
    }

    /**
     * 获取完整请求
     */
    public function getRequestInfo(): array
    {
        $request = $this->request;
        $requestInfo = [
            'ip' => $request->ip(),
            'method' => $request->method(),
            'host' => $request->host(),
            'uri' => $request->url(),
        ];
        return [
            "{$requestInfo['ip']} {$requestInfo['method']} {$requestInfo['host']}{$requestInfo['uri']}",
            '[ ROUTE ] ' . var_export($this->getRouteInfo(), true),
            '[ HEADER ] ' . var_export($request->header(), true),
            '[ PARAM ] ' . var_export($request->param(), true),
        ];
    }
}
